<template>
  <div class="ai-assistant">
    <el-card class="assistant-card">
              <template #header>
          <div class="card-header">
            <h2><ChatDotRound /> AI编程助手</h2>
            <div class="header-controls">
              <div class="typing-speed-control">
                <span>打字速度:</span>
                <el-select v-model="typingSpeed" size="small" style="width: 100px; margin-left: 8px;">
                  <el-option label="快速" :value="15" />
                  <el-option label="正常" :value="30" />
                  <el-option label="慢速" :value="50" />
                  <el-option label="极慢" :value="80" />
                </el-select>
              </div>
              <div class="function-tabs">
                <el-radio-group v-model="currentFunction" size="small">
                  <el-radio-button label="chat">智能对话</el-radio-button>
                  <el-radio-button label="code-review">代码审查</el-radio-button>
                  <el-radio-button label="learning-guide">学习指导</el-radio-button>
                  <el-radio-button label="debug-help">调试帮助</el-radio-button>
                  <el-radio-button label="practice">练习建议</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </div>
        </template>

      <!-- 智能对话界面 -->
      <div v-if="currentFunction === 'chat'" class="chat-interface">
        <div class="messages-container" ref="messagesContainer">
                      <div
              v-for="(message, index) in messages"
              :key="index"
              :class="['message', message.type]"
            >
              <div class="message-content">
                <div v-if="message.isThinking" class="thinking-indicator">
                  <div class="thinking-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                  <div class="thinking-text">AI正在思考中...</div>
                </div>
                <div v-else class="message-text" v-html="formatMessage(message.content)"></div>
                <span v-if="message.isTyping" class="typing-cursor">|</span>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>
        </div>
        
        <div class="input-area">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入你的问题..."
            @keyup.enter.ctrl="sendMessage"
          />
          <el-button
            type="primary"
            @click="sendMessage"
            :loading="loading"
            :disabled="!inputMessage.trim()"
          >
            发送 (Ctrl+Enter)
          </el-button>
          <div v-if="isTyping" class="typing-hint">
            按空格键跳过打字效果
          </div>
        </div>
      </div>

      <!-- 代码审查界面 -->
      <div v-if="currentFunction === 'code-review'" class="code-review-interface">
        <el-form :model="codeReviewForm" label-width="100px">
          <el-form-item label="编程语言">
            <el-select v-model="codeReviewForm.language" placeholder="选择语言">
              <el-option label="Python" value="python" />
              <el-option label="JavaScript" value="javascript" />
              <el-option label="Java" value="java" />
              <el-option label="C++" value="cpp" />
              <el-option label="C" value="c" />
            </el-select>
          </el-form-item>
          <el-form-item label="代码">
            <el-input
              v-model="codeReviewForm.code"
              type="textarea"
              :rows="10"
              placeholder="请输入要审查的代码..."
            />
          </el-form-item>
          <el-form-item>
                      <el-button type="primary" @click="submitCodeReview" :loading="loading">
            开始审查
          </el-button>
          <div v-if="isTyping" class="typing-hint">
            按空格键跳过打字效果
          </div>
          </el-form-item>
        </el-form>
        
        <div v-if="isThinking" class="thinking-status">
          <div class="thinking-indicator">
            <div class="thinking-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
            <div class="thinking-text">AI正在分析代码...</div>
          </div>
        </div>
        
        <div v-if="codeReviewResult" class="review-result">
          <h3>审查结果</h3>
          <div class="result-content" v-html="formatMessage(codeReviewResult)"></div>
          <span v-if="isTyping" class="typing-cursor">|</span>
        </div>
      </div>

      <!-- 学习指导界面 -->
      <div v-if="currentFunction === 'learning-guide'" class="learning-guide-interface">
        <el-form :model="learningGuideForm" label-width="100px">
          <el-form-item label="学习主题">
            <el-input
              v-model="learningGuideForm.topic"
              placeholder="例如：Python基础、数据结构、算法等"
            />
          </el-form-item>
          <el-form-item label="学习水平">
            <el-select v-model="learningGuideForm.userLevel" placeholder="选择水平">
              <el-option label="初学者" value="beginner" />
              <el-option label="进阶" value="intermediate" />
              <el-option label="高级" value="advanced" />
            </el-select>
          </el-form-item>
          <el-form-item>
                      <el-button type="primary" @click="submitLearningGuide" :loading="loading">
            生成学习指导
          </el-button>
          <div v-if="isTyping" class="typing-hint">
            按空格键跳过打字效果
          </div>
          </el-form-item>
        </el-form>
        
        <div v-if="isThinking" class="thinking-status">
          <div class="thinking-indicator">
            <div class="thinking-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
            <div class="thinking-text">AI正在制定学习计划...</div>
          </div>
        </div>
        
        <div v-if="learningGuideResult" class="guide-result">
          <h3>学习指导</h3>
          <div class="result-content" v-html="formatMessage(learningGuideResult)"></div>
          <span v-if="isTyping" class="typing-cursor">|</span>
        </div>
      </div>

      <!-- 调试帮助界面 -->
      <div v-if="currentFunction === 'debug-help'" class="debug-help-interface">
        <el-form :model="debugHelpForm" label-width="100px">
          <el-form-item label="错误信息">
            <el-input
              v-model="debugHelpForm.errorMessage"
              type="textarea"
              :rows="3"
              placeholder="请粘贴错误信息..."
            />
          </el-form-item>
          <el-form-item label="相关代码">
            <el-input
              v-model="debugHelpForm.code"
              type="textarea"
              :rows="8"
              placeholder="请输入相关的代码（可选）..."
            />
          </el-form-item>
          <el-form-item label="编程语言">
            <el-select v-model="debugHelpForm.language" placeholder="选择语言">
              <el-option label="Python" value="python" />
              <el-option label="JavaScript" value="javascript" />
              <el-option label="Java" value="java" />
              <el-option label="C++" value="cpp" />
              <el-option label="C" value="c" />
            </el-select>
          </el-form-item>
          <el-form-item>
                      <el-button type="primary" @click="submitDebugHelp" :loading="loading">
            获取调试帮助
          </el-button>
          <div v-if="isTyping" class="typing-hint">
            按空格键跳过打字效果
          </div>
          </el-form-item>
        </el-form>
        
        <div v-if="isThinking" class="thinking-status">
          <div class="thinking-indicator">
            <div class="thinking-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
            <div class="thinking-text">AI正在分析错误...</div>
          </div>
        </div>
        
        <div v-if="debugHelpResult" class="debug-result">
          <h3>调试建议</h3>
          <div class="result-content" v-html="formatMessage(debugHelpResult)"></div>
          <span v-if="isTyping" class="typing-cursor">|</span>
        </div>
      </div>

      <!-- 练习建议界面 -->
      <div v-if="currentFunction === 'practice'" class="practice-interface">
        <el-form :model="practiceForm" label-width="100px">
          <el-form-item label="编程水平">
            <el-select v-model="practiceForm.userLevel" placeholder="选择水平">
              <el-option label="初学者" value="beginner" />
              <el-option label="进阶" value="intermediate" />
              <el-option label="高级" value="advanced" />
            </el-select>
          </el-form-item>
          <el-form-item label="兴趣领域">
            <el-select
              v-model="practiceForm.interests"
              multiple
              placeholder="选择感兴趣的领域"
            >
              <el-option label="Web开发" value="web" />
              <el-option label="数据科学" value="data" />
              <el-option label="算法竞赛" value="algorithm" />
              <el-option label="移动开发" value="mobile" />
              <el-option label="系统编程" value="system" />
              <el-option label="人工智能" value="ai" />
            </el-select>
          </el-form-item>
          <el-form-item>
                      <el-button type="primary" @click="submitPracticeSuggestions" :loading="loading">
            获取练习建议
          </el-button>
          <div v-if="isTyping" class="typing-hint">
            按空格键跳过打字效果
          </div>
          </el-form-item>
        </el-form>
        
        <div v-if="isThinking" class="thinking-status">
          <div class="thinking-indicator">
            <div class="thinking-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
            <div class="thinking-text">AI正在生成练习建议...</div>
          </div>
        </div>
        
        <div v-if="practiceResult" class="practice-result">
          <h3>练习建议</h3>
          <div class="result-content" v-html="formatMessage(practiceResult)"></div>
          <span v-if="isTyping" class="typing-cursor">|</span>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import api from '@/api'

const authStore = useAuthStore()
const currentFunction = ref('chat')

// 聊天相关
const messages = reactive([
  {
    type: 'assistant',
    content: '你好！我是AI编程助手，有什么可以帮助你的吗？我可以帮你：\n\n• 解答编程问题\n• 审查和改进代码\n• 制定学习计划\n• 提供调试帮助\n• 推荐练习项目\n\n请选择上方功能或直接开始对话！',
    timestamp: new Date(),
    isTyping: false
  }
])
const inputMessage = ref('')
const loading = ref(false)
const messagesContainer = ref(null)
const typingSpeed = ref(30) // 打字速度（毫秒/字符）
const isTyping = ref(false) // 是否正在打字
const isThinking = ref(false) // 是否正在思考
const thinkingStartTime = ref(null) // 思考开始时间
const thinkingDuration = ref(0) // 思考持续时间

// 代码审查相关
const codeReviewForm = reactive({
  code: '',
  language: 'python'
})
const codeReviewResult = ref('')

// 学习指导相关
const learningGuideForm = reactive({
  topic: '',
  userLevel: 'beginner'
})
const learningGuideResult = ref('')

// 调试帮助相关
const debugHelpForm = reactive({
  errorMessage: '',
  code: '',
  language: 'python'
})
const debugHelpResult = ref('')

// 练习建议相关
const practiceForm = reactive({
  userLevel: 'beginner',
  interests: []
})
const practiceResult = ref('')

// 逐字打字效果（聊天消息）
const typeMessage = async (fullContent, messageIndex) => {
  const message = messages[messageIndex]
  message.content = ''
  message.isTyping = true
  isTyping.value = true
  
  for (let i = 0; i < fullContent.length; i++) {
    const char = fullContent[i]
    message.content += char
    
    // 根据字符类型调整延迟
    let delay = typingSpeed.value
    if (char === '\n') {
      delay = typingSpeed.value * 3 // 换行符延迟更长
    } else if (char === ' ' || char === '\t') {
      delay = typingSpeed.value * 0.5 // 空格延迟更短
    } else if (char === '.' || char === '!' || char === '?') {
      delay = typingSpeed.value * 2 // 标点符号延迟稍长
    }
    
    await new Promise(resolve => setTimeout(resolve, delay))
    
    // 每10个字符滚动一次，提高性能
    if (i % 10 === 0) {
      await nextTick()
      scrollToBottom()
    }
  }
  
  message.isTyping = false
  isTyping.value = false
  await nextTick()
  scrollToBottom()
}

// 逐字打字效果（结果文本）
const typeResult = async (fullContent, resultRef) => {
  let result
  switch (resultRef) {
    case 'codeReviewResult':
      result = codeReviewResult
      break
    case 'learningGuideResult':
      result = learningGuideResult
      break
    case 'debugHelpResult':
      result = debugHelpResult
      break
    case 'practiceResult':
      result = practiceResult
      break
    default:
      return
  }
  result.value = ''
  isTyping.value = true
  
  for (let i = 0; i < fullContent.length; i++) {
    const char = fullContent[i]
    result.value += char
    
    // 根据字符类型调整延迟
    let delay = typingSpeed.value
    if (char === '\n') {
      delay = typingSpeed.value * 3 // 换行符延迟更长
    } else if (char === ' ' || char === '\t') {
      delay = typingSpeed.value * 0.5 // 空格延迟更短
    } else if (char === '.' || char === '!' || char === '?') {
      delay = typingSpeed.value * 2 // 标点符号延迟稍长
    }
    
    await new Promise(resolve => setTimeout(resolve, delay))
    
    // 每10个字符更新一次，提高性能
    if (i % 10 === 0) {
      await nextTick()
    }
  }
  
  isTyping.value = false
  await nextTick()
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return
  const message = inputMessage.value.trim()
  inputMessage.value = ''
  console.log('发送消息:', message)

  const userMessage = {
    type: 'user',
    content: message,
    timestamp: new Date(),
    isTyping: false
  }
  messages.push(userMessage)

  // 显示思考状态
  isThinking.value = true
  thinkingStartTime.value = Date.now()
  thinkingDuration.value = 0
  
  // 启动思考时间计时器
  const thinkingTimer = setInterval(() => {
    if (isThinking.value) {
      thinkingDuration.value = Math.floor((Date.now() - thinkingStartTime.value) / 1000)
    } else {
      clearInterval(thinkingTimer)
    }
  }, 1000)
  
  const thinkingMessage = {
    type: 'assistant',
    content: '',
    timestamp: new Date(),
    isThinking: true
  }
  messages.push(thinkingMessage)
  await nextTick()
  scrollToBottom()

  loading.value = true
  try {
    console.log('调用AI助手API...')
    const response = await api.post('/assistant/chat', {
      message,
      context: {
        user_level: authStore.user?.level || 'beginner'
      }
    })
    console.log('API响应:', response)
    
    // 移除思考消息
    messages.pop()
    isThinking.value = false
    thinkingStartTime.value = null
    thinkingDuration.value = 0
    
    if (response && response.response) {
      const assistantMessage = {
        type: 'assistant',
        content: '', // 初始为空，等待逐字显示
        timestamp: new Date(),
        isTyping: true
      }
      messages.push(assistantMessage)
      
      // 开始逐字打字效果
      await typeMessage(response.response, messages.length - 1)
    } else {
      console.error('响应格式错误:', response)
      ElMessage.error('AI助手回复格式错误')
    }
    loading.value = false
    await nextTick()
    console.log('滚动到底部，消息容器:', messagesContainer.value)
    scrollToBottom()
  } catch (error) {
    console.error('AI助手错误:', error)
    // 移除思考消息
    if (isThinking.value) {
      messages.pop()
      isThinking.value = false
      thinkingStartTime.value = null
      thinkingDuration.value = 0
    }
    
    let errorMessage = 'AI助手暂时不可用，请稍后重试'
    
    if (error.response) {
      errorMessage = error.response.data?.message || errorMessage
    } else if (error.request) {
      if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时，请稍后重试'
      } else {
        errorMessage = '网络连接失败，请检查网络'
      }
    } else {
      errorMessage = error.message || errorMessage
    }
    
    ElMessage.error(errorMessage)
    loading.value = false
  }
}

// 代码审查
const submitCodeReview = async () => {
  if (!codeReviewForm.code.trim()) {
    ElMessage.warning('请输入要审查的代码')
    return
  }
  
  loading.value = true
  isThinking.value = true
  thinkingStartTime.value = Date.now()
  thinkingDuration.value = 0
  
  // 启动思考时间计时器
  const thinkingTimer = setInterval(() => {
    if (isThinking.value) {
      thinkingDuration.value = Math.floor((Date.now() - thinkingStartTime.value) / 1000)
    } else {
      clearInterval(thinkingTimer)
    }
  }, 1000)
  
  try {
    const response = await api.post('/assistant/code-review', {
      code: codeReviewForm.code,
      language: codeReviewForm.language,
      user_level: authStore.user?.level || 'beginner'
    })
    
    if (response && response.review) {
      // 清空之前的结果
      codeReviewResult.value = ''
      // 开始逐字打字效果
      await typeResult(response.review, 'codeReviewResult')
    } else {
      ElMessage.error('代码审查失败')
    }
  } catch (error) {
    console.error('代码审查错误:', error)
    let errorMessage = '代码审查失败，请稍后重试'
    
    if (error.response) {
      errorMessage = error.response.data?.message || errorMessage
    } else if (error.request) {
      if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时，请稍后重试'
      } else {
        errorMessage = '网络连接失败，请检查网络'
      }
    } else {
      errorMessage = error.message || errorMessage
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
    isThinking.value = false
    thinkingStartTime.value = null
    thinkingDuration.value = 0
  }
}

// 学习指导
const submitLearningGuide = async () => {
  if (!learningGuideForm.topic.trim()) {
    ElMessage.warning('请输入学习主题')
    return
  }
  
  loading.value = true
  isThinking.value = true
  try {
    const response = await api.post('/assistant/learning-guide', {
      topic: learningGuideForm.topic,
      user_level: learningGuideForm.userLevel
    })
    
    if (response && response.guide) {
      // 清空之前的结果
      learningGuideResult.value = ''
      // 开始逐字打字效果
      await typeResult(response.guide, 'learningGuideResult')
    } else {
      ElMessage.error('学习指导生成失败')
    }
  } catch (error) {
    console.error('学习指导错误:', error)
    let errorMessage = '学习指导生成失败，请稍后重试'
    
    if (error.response) {
      // 服务器返回错误
      errorMessage = error.response.data?.message || errorMessage
    } else if (error.request) {
      // 网络错误
      if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时，请稍后重试'
      } else {
        errorMessage = '网络连接失败，请检查网络'
      }
    } else {
      // 其他错误
      errorMessage = error.message || errorMessage
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
    isThinking.value = false
  }
}

// 调试帮助
const submitDebugHelp = async () => {
  if (!debugHelpForm.errorMessage.trim()) {
    ElMessage.warning('请输入错误信息')
    return
  }
  
  loading.value = true
  isThinking.value = true
  try {
    const response = await api.post('/assistant/debug-help', {
      error_message: debugHelpForm.errorMessage,
      code: debugHelpForm.code,
      language: debugHelpForm.language
    })
    
    if (response && response.debug_help) {
      // 清空之前的结果
      debugHelpResult.value = ''
      // 开始逐字打字效果
      await typeResult(response.debug_help, 'debugHelpResult')
    } else {
      ElMessage.error('调试帮助生成失败')
    }
  } catch (error) {
    console.error('调试帮助错误:', error)
    let errorMessage = '调试帮助生成失败，请稍后重试'
    
    if (error.response) {
      errorMessage = error.response.data?.message || errorMessage
    } else if (error.request) {
      if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时，请稍后重试'
      } else {
        errorMessage = '网络连接失败，请检查网络'
      }
    } else {
      errorMessage = error.message || errorMessage
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
    isThinking.value = false
  }
}

// 练习建议
const submitPracticeSuggestions = async () => {
  loading.value = true
  isThinking.value = true
  try {
    const response = await api.post('/assistant/practice-suggestions', {
      user_level: practiceForm.userLevel,
      interests: practiceForm.interests
    })
    
    if (response && response.suggestions) {
      // 清空之前的结果
      practiceResult.value = ''
      // 开始逐字打字效果
      await typeResult(response.suggestions, 'practiceResult')
    } else {
      ElMessage.error('练习建议生成失败')
    }
  } catch (error) {
    console.error('练习建议错误:', error)
    let errorMessage = '练习建议生成失败，请稍后重试'
    
    if (error.response) {
      errorMessage = error.response.data?.message || errorMessage
    } else if (error.request) {
      if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时，请稍后重试'
      } else {
        errorMessage = '网络连接失败，请检查网络'
      }
    } else {
      errorMessage = error.message || errorMessage
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
    isThinking.value = false
  }
}

// 格式化消息内容
const formatMessage = (content) => {
  if (!content) return ''
  return content
    .replace(/\n/g, '<br>')
    .replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
    .replace(/`([^`]+)`/g, '<code>$1</code>')
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      // 使用平滑滚动效果
      messagesContainer.value.scrollTo({
        top: messagesContainer.value.scrollHeight,
        behavior: 'smooth'
      })
    }
  })
}

// 跳过打字效果
const skipTyping = () => {
  if (isTyping.value) {
    // 找到正在打字的消息并完成
    const typingMessage = messages.find(msg => msg.isTyping)
    if (typingMessage) {
      typingMessage.isTyping = false
      isTyping.value = false
    }
    
    // 完成结果文本的打字效果
    if (codeReviewResult.value && codeReviewResult.value.length > 0) {
      // 结果已经显示，只是停止打字状态
      isTyping.value = false
    }
  }
}

// 键盘事件监听
const handleKeydown = (event) => {
  if (event.code === 'Space' && isTyping.value) {
    event.preventDefault()
    skipTyping()
  }
}

onMounted(() => {
  nextTick(() => {
    scrollToBottom()
  })
  
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeydown)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 监听消息数组变化
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })
</script>

<style scoped>
.ai-assistant {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.assistant-card {
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止内容溢出 */
  position: relative; /* 为粘性定位提供参考 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 20px;
}

.typing-speed-control {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.function-tabs {
  margin-left: 0;
}

/* 聊天界面样式 */
.chat-interface {
  display: flex;
  flex-direction: column;
  height: calc(100% - 60px); /* 减去header高度 */
  min-height: 400px;
  position: relative;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 0; /* 移除底部边距，因为输入框现在是粘性定位 */
  min-height: 200px;
  max-height: calc(100vh - 400px); /* 为输入框预留更多空间 */
  padding-bottom: 140px; /* 为粘性输入框预留空间 */
}

.message {
  margin-bottom: 20px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.assistant {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
}

.message.user .message-content {
  background: #007bff;
  color: white;
}

.message.assistant .message-content {
  background: white;
  border: 1px solid #e9ecef;
}

.message-text {
  margin-bottom: 8px;
  line-height: 1.5;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  text-align: right;
}

.typing-cursor {
  display: inline-block;
  width: 2px;
  height: 1.2em;
  background-color: #007bff;
  animation: blink 1s infinite;
  margin-left: 2px;
  vertical-align: middle;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.thinking-indicator {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.thinking-dots {
  display: flex;
  gap: 4px;
}

.thinking-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #007bff;
  animation: thinking 1.4s infinite ease-in-out;
}

.thinking-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.thinking-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

.thinking-dots span:nth-child(3) {
  animation-delay: 0s;
}

@keyframes thinking {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.thinking-text {
  font-size: 14px;
  color: #666;
  font-style: italic;
}

.thinking-status {
  margin: 20px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}



.input-area {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  flex-shrink: 0; /* 防止输入区域被压缩 */
  position: sticky; /* 粘性定位 */
  bottom: 0; /* 固定在底部 */
  background: white; /* 确保背景色 */
  padding: 20px;
  border-top: 1px solid #e9ecef;
  z-index: 10; /* 确保在最上层 */
}

.input-area .el-textarea {
  flex: 1;
  min-height: 80px; /* 确保输入框有足够高度 */
  max-height: 120px; /* 限制最大高度 */
}

.typing-hint {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 8px;
  animation: fadeInOut 2s infinite;
}

@keyframes fadeInOut {
  0%, 100% { opacity: 0.5; }
  50% { opacity: 1; }
}

/* 其他功能界面样式 */
.code-review-interface,
.learning-guide-interface,
.debug-help-interface,
.practice-interface {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  padding-bottom: 40px;
  min-height: 400px;
  
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

.code-review-interface::-webkit-scrollbar,
.learning-guide-interface::-webkit-scrollbar,
.debug-help-interface::-webkit-scrollbar,
.practice-interface::-webkit-scrollbar {
  width: 8px;
}

.code-review-interface::-webkit-scrollbar-track,
.learning-guide-interface::-webkit-scrollbar-track,
.debug-help-interface::-webkit-scrollbar-track,
.practice-interface::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.code-review-interface::-webkit-scrollbar-thumb,
.learning-guide-interface::-webkit-scrollbar-thumb,
.debug-help-interface::-webkit-scrollbar-thumb,
.practice-interface::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.code-review-interface::-webkit-scrollbar-thumb:hover,
.learning-guide-interface::-webkit-scrollbar-thumb:hover,
.debug-help-interface::-webkit-scrollbar-thumb:hover,
.practice-interface::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.review-result,
.guide-result,
.debug-result,
.practice-result {
  margin-top: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #007bff;
  position: relative;
}

.result-content {
  line-height: 1.6;
  position: relative;
  max-height: 400px;
  overflow-y: auto;
  padding-right: 10px;
  
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

.result-content::-webkit-scrollbar {
  width: 6px;
}

.result-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.result-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.result-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.result-content pre {
  background: #f1f3f4;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
}

.result-content code {
  background: #f1f3f4;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
}

/* 结果区域的打字光标样式 */
.review-result .typing-cursor,
.guide-result .typing-cursor,
.debug-result .typing-cursor,
.practice-result .typing-cursor {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-assistant {
    padding: 10px;
  }
  
  .assistant-card {
    height: calc(100vh - 20px);
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .header-controls {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  
  .typing-speed-control {
    justify-content: center;
  }
  
  .function-tabs {
    margin-left: 0;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .input-area {
    flex-direction: column;
    padding: 15px;
  }
  
  .messages-container {
    padding-bottom: 160px; /* 移动端为输入框预留更多空间 */
  }
  
  .code-review-interface,
  .learning-guide-interface,
  .debug-help-interface,
  .practice-interface {
    padding: 15px;
    padding-bottom: 30px;
  }
  
  .result-content {
    max-height: 300px;
  }
}

/* 小屏幕优化 */
@media (max-height: 600px) {
  .assistant-card {
    height: calc(100vh - 20px);
  }
  
  .messages-container {
    max-height: calc(100vh - 300px);
    padding-bottom: 120px;
  }
  
  .code-review-interface,
  .learning-guide-interface,
  .debug-help-interface,
  .practice-interface {
    min-height: 300px;
  }
  
  .result-content {
    max-height: 200px;
  }
}

/* 确保在小屏幕上输入框不会被隐藏 */
@media (max-height: 600px) {
  .assistant-card {
    height: 90vh;
  }
  
  .messages-container {
    max-height: calc(100vh - 350px);
    padding-bottom: 120px;
  }
}
</style>
